<template>
	<div
		class="import"
		v-loading="submiting"
		:element-loading-text="submitingTip"
	>
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">投保信息</span>
				<el-radio-group v-model="policyholder" style="margin: 0 30px 4px">
					<el-radio label="corporate">团体客户</el-radio>
					<el-radio label="individual">个人客户</el-radio>
				</el-radio-group>
			</div>
			<el-form
				v-show="policyholder === 'corporate'"
				:model="customerForm.corporate"
				label-width="130px"
				ref="corporate"
				:rules="corporateRules"
			>
				<el-form-item label="营业执照" prop="license">
					<div style="display: inline-block; width: 100%">
						<upload
							count="1"
							:value="customerForm.corporate.license"
							@input="onUploadLicenseOcr"
						></upload>
					</div>
				</el-form-item>
				<el-form-item label="企业名称" prop="customerName">
					<div class="field grid" cloumn="1fr auto">
						<el-input
							v-model="customerForm.corporate.customerName"
							placeholder="请输入企业客户名称"
						/>
					</div>
				</el-form-item>
				<el-form-item label="统一社会信用代码" prop="certNum">
					<el-input
						v-model="customerForm.corporate.certNum"
						class="field"
						placeholder="请输入证件号码"
					/>
				</el-form-item>
				<el-form-item label="联系人" prop="contactName">
					<el-input
						v-model="customerForm.corporate.contactName"
						class="field"
						placeholder="请输入联系人"
					/>
				</el-form-item>

				<el-form-item label="手机号码" prop="contactPhone">
					<el-input
						v-model="customerForm.corporate.contactPhone"
						class="field"
						maxlength="11"
						placeholder="请输入手机号码"
					/>
				</el-form-item>

				<el-form-item label="地址" prop="address">
					<el-input
						v-model="customerForm.corporate.address"
						class="field"
						maxlength="11"
						placeholder="请输入地址"
					/>
				</el-form-item>
			</el-form>

			<el-form
				v-show="policyholder === 'individual'"
				:model="customerForm.individual"
				label-width="130px"
				ref="individual"
				:rules="individualRules"
			>
				<el-form-item label="身份证" prop="idCard">
					<div style="display: inline-block; width: 100%">
						<upload
							count="1"
							:value="customerForm.individual.idCard"
							@input="onUploadCard"
						></upload>
					</div>
				</el-form-item>
				<el-form-item label="客户名称" prop="name">
					<el-input
						v-model="customerForm.individual.name"
						placeholder="请输入客户名称"
					/>
				</el-form-item>
				<el-form-item label="证件类型" prop="idType">
					<el-select
						v-model="customerForm.individual.idType"
						class="field"
						placeholder="请输入证件类型"
						@change="setIndividualBirth"
					>
						<el-option
							v-for="item in idTypeOptions"
							:key="item.value"
							:label="item.name"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="证件号码" prop="idNumber">
					<el-input
						v-model="customerForm.individual.idNumber"
						class="field"
						placeholder="请输入证件号码"
						@input="setIndividualBirth"
					/>
				</el-form-item>
				<el-form-item label="手机号码" prop="contactPhone">
					<el-input
						v-model="customerForm.individual.contactPhone"
						class="field"
						maxlength="11"
						placeholder="请输入手机号码"
					/>
				</el-form-item>
				<el-form-item label="地址" prop="address">
					<el-input
						v-model="customerForm.individual.address"
						class="field"
						maxlength="11"
						placeholder="请输入地址"
					/>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- <el-card class="box-card" v-if="activeProduct">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">保障详情</span>
			</div>
		
		</el-card> -->

		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">车辆信息</span>
			</div>
			<el-form
				:model="customerForm.carInfo"
				label-width="130px"
				ref="carIndo"
				:rules="carIndoRules"
			>
				<el-form-item label="行驶证" prop="drive">
					<div style="display: inline-block; width: 100%">
						<upload
							count="1"
							:value="customerForm.carInfo.drive"
							@input="onUploadDrive"
						></upload>
					</div>
				</el-form-item>
				<el-form-item label="车牌号" prop="licensePlate" required>
					<el-input
						v-model="customerForm.carInfo.licensePlate"
						placeholder="请输入车牌号"
					/>
				</el-form-item>
				<el-form-item label="车架号" prop="vin" required>
					<el-input
						v-model="customerForm.carInfo.vin"
						placeholder="请输入车架号"
					/>
				</el-form-item>
				<el-form-item label="核定载人数" prop="approvedSeating">
					<el-input
						v-model="customerForm.carInfo.approvedSeating"
						class="field"
						placeholder="请输入证件号码"
					/>
				</el-form-item>
				<el-form-item label="吨位" prop="tonnage">
					<el-input
						v-model="customerForm.carInfo.tonnage"
						class="field"
						placeholder="请输入总质量"
						suffix="kg"
					/>
				</el-form-item>
				<el-form-item label="发动机号" prop="engineNumber">
					<el-input
						v-model="customerForm.carInfo.engineNumber"
						class="field"
						maxlength="11"
						placeholder="请输入发动机号"
					/>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card class="box-card" v-if="productDetail">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">选择方案</span>
			</div>
			<div
				v-loading="detailLoading"
				style="
					overflow-y: auto;
					max-height: 250px;
					min-height: 100px;
					margin: -5px;
				"
			>
				<div
					style="
						display: inline-block;
						width: 240px;
						margin: 0 10px 10px 0;
						border: 2px solid #e8e8e8;
						border-radius: 12px;
						padding: 15px 15px;
					"
					v-for="guarantee in productDetail.guarantees"
					:key="guarantee.name"
					:style="{
						borderColor: activeGua == guarantee ? '#5f88ff' : '#e8e8e8'
					}"
					@click="activeGua = guarantee"
				>
					<div style="margin-bottom: 12px">{{ guarantee.name }}</div>

					<div
						style="display: grid; grid-template-columns: 1fr auto; gap: 5px"
						v-for="detail in guarantee.detail"
					>
						<span class="">{{ detail.protection }}</span>
						<span class="" :title="detail.coverage">{{ detail.coverage }}</span>
					</div>
				</div>
			</div>
		</el-card>

		<el-dialog :title="agreeLabel" :visible.sync="agreeShow" top="10vh">
			<div
				v-html="productDetail[agreeProp]"
				style="max-height: 60vh; overflow-y: scroll"
			></div>
		</el-dialog>
		<div class="submit" v-if="productId">
			<div class="agree">
				<el-checkbox
					v-model="agreeCheck"
					size="large"
					class="check"
				></el-checkbox>
				<span>我已阅读并同意</span>
				<!-- <a href="./客户告知书.docx" style="cursor: pointer; color: #5f88ff"
					>《客户告知书》</a
				> -->
				<span
					style="cursor: pointer; color: #5f88ff"
					v-for="agree in agrees"
					:key="agree.name"
					@click="() => onAgree(agree)"
					>《{{ agree.label }}》</span
				>
			</div>
			<div class="submit-btn button" @click="save">提交订单</div>
		</div>
		<!-- <div style="margin-block: 20px; text-align: center" v-if="productId">
			<el-button @click="save" type="primary" size="mini">提交订单</el-button>
		</div> -->
	</div>
</template>

<script>
import {
	productDetail,
	createBusiness,
	licenseOcr,
	list as FetchProductList,
	idCardOcr,
	driveOcr,
	goPay
} from '@/api'
import _ from 'lodash'
import moment from 'moment'
import ProductItem from '@/views/components/product-item.vue'
import { transformKey, getAgeByNo, getAgeByBirth, getBirth } from '@/utils'
import InsureAddress from './components/insure-address.vue'
import Upload from '@/components/form/fields/upload.vue'

const agrees = [
	{
		name: 'specialAgreement',
		label: '特别约定'
	},
	{
		name: 'insuranceNotice',
		label: '投保须知'
	},
	{
		name: 'claimsNotice',
		label: '理赔须知'
	},
	{
		name: 'exclusion',
		label: '免责声明'
	}
]
export default {
	data() {
		return {
			activeGua: {},
			getAgeByNo, // 计算年龄
			getAgeByBirth, //计算年龄
			submitingTip: '', // 等待中提示
			policyholder: 'corporate', // 投保人类型

			submiting: false,
			paymentLoading: false,
			agrees,
			activeProduct: '',
			productList: [],
			businessId: '',

			// 保障期限
			qixianForm: {
				startTime: '',
				endTime: ''
			},
			qixianRules: {
				startTime: [{ required: true, message: '请选择保障起期' }],
				endTime: [{ required: true, message: '请选择保障止期' }]
			},
			qixianLoading: false,

			paymentForm: {
				payer: process.env.NODE_ENV === 'development' ? '' : '',
				payerCardNum: process.env.NODE_ENV === 'development' ? '' : ''
			},
			paymentRules: {
				payer: [{ required: true, message: '请填写支付人' }],
				payerCardNum: [{ required: true, message: '请填写支付人证件号码' }]
			},
			paymentLoading: false,
			// 人员信息
			personTableFields: [],
			personList: [],
			importLoading: false, // 导入loading
			personLoading: false, // 人员保存loading
			detailLoading: false, // 获取详情
			productDetail: {}, // 当前产品详情（协议
			agreeShow: false, // 协议弹窗
			agreeProp: '', // 协议类型

			agreeCheck: false, // 是否勾选协议
			customerHistories: [], // 常用客户
			personHistories: [], // 常用客户
			customerForm: {
				corporate: {
					customerName: '', // 客户名称
					contactName: '', // 联系人姓名
					contactPhone: '', // 联系电话
					address: '', // 地址
					certNum: '',
					license: []
				}, // 团体客户
				individual: {
					name: '', // 客户名称
					idType: '', // 证件类型
					idNumber: '', // 证件号码
					contactPhone: '', //手机号
					birthday: '', // 出生日期（个人客户专用）
					gender: '', // 性别（1表示男性，0表示女性）
					address: '', // 地址
					idCard: [] // 身份证照片
				}, //个人客户
				carInfo: {
					licensePlate: '',
					vin: '', //车架号
					approvedSeating: '',
					tonnage: '',
					engineNumber: '',
					drive: []
				}
			},
			corporateRules: {
				customerName: [
					{ required: true, message: '请输入客户名称', trigger: 'submit' }
				],
				contactName: [
					{ required: true, message: '请输入联系人姓名', trigger: 'submit' }
				],
				certNum: [
					{
						required: true,
						message: '请输入统一社会信用代码',
						trigger: 'submit'
					}
				],
				license: [
					{ required: true, message: '请上传营业执照', trigger: 'submit' }
				],
				contactPhone: [
					{ required: true, message: '请输入联系人电话', trigger: 'submit' }
				],
				address: [
					{ required: true, message: '请输入详细地址', trigger: 'submit' }
				],
				postcode: [
					{ required: true, message: '请输入邮政编码', trigger: 'submit' }
				]
			},
			individualRules: {
				idCard: [
					{ required: true, message: '请输入身份证', trigger: 'submit' }
				],
				name: [
					{ required: true, message: '请输入客户名称', trigger: 'submit' }
				],
				idType: [
					{ required: true, message: '请选择证件类型', trigger: 'submit' }
				],
				idNumber: [
					{ required: true, message: '请输入证件号码', trigger: 'submit' }
				],
				birthDate: [
					{ required: true, message: '请输入出生日期', trigger: 'submit' }
				],
				gender: [{ required: true, message: '请选择性别', trigger: 'submit' }],
				contactPhone: [
					{ required: true, message: '请选择手机号', trigger: 'submit' }
				],
				address: [{ required: true, message: '请选择地址', trigger: 'submit' }]
			},
			carIndoRules: {
				licensePlate: [
					{ required: true, message: '请输入车牌号', trigger: 'submit' }
				],
				vin: [{ required: true, message: '请输入车架号', trigger: 'submit' }],
				approvedSeating: [
					{ required: true, message: '请输入核定载人数', trigger: 'submit' }
				],
				tonnage: [
					{ required: true, message: '请输入总质量', trigger: 'submit' }
				],
				engineNumber: [
					{ required: true, message: '请输入发动机号', trigger: 'submit' }
				],
				drive: [{ required: true, message: '请上传行驶证', trigger: 'submit' }]
			},

			idTypeOptions: [
				{ name: '身份证', value: 0 },
				{ name: '出生证', value: 1 },
				{ name: '护照', value: 2 },
				{ name: '军人证', value: 3 },
				{ name: '在华居住证', value: 4 },
				{ name: '台湾居民往来大陆通行证', value: 5 },
				{ name: '港澳居民往来内地通行证', value: 6 },
				{ name: '国人永久居留身份证', value: 7 },
				{ name: '居民户口簿', value: 8 }
			],
			// paymentShow: false,

			corporateAddress: '', // 详细信息填写 临时框
			beRules: {
				be_birth: [{ required: true, message: '请输入监护人出生日期' }],
				be_gender: [{ required: true, message: '请选择监护人性别' }],
				be_id_num: [{ required: true, message: '请输入监护人证件号码' }],
				be_id_type: [{ required: true, message: '请选择监护人证件类型' }],
				be_name: [{ required: true, message: '请输入监护人姓名' }],
				be_phone: [{ required: true, message: '请输入监护人手机号' }]
			}
		}
	},
	computed: {
		productId() {
			return this.$route.query.productId || 11653
		},
		agreeLabel() {
			var curAgree = this.agrees.find((agree) => agree.name === this.agreeProp)
			return curAgree ? curAgree.label : ''
		},
		qixianQiffTime() {
			const { startTime, endTime } = this.qixianForm
			const days = moment(endTime).diff(moment(startTime), 'days') || 0
			return days + 1 + '天'
		},
		defaultOpenExpand() {
			// 因未满18岁 需要填写监护人
			return this.personList
				.map((item) => item.birth)
				.filter((birth) => birth && getAgeByBirth(birth) < 18)
		}
	},
	created() {
		this.fetchProductDetail()
		createBusiness({ productId: this.productId }).then((res) => {
			this.businessId = res.data.businessId
		})
	},
	watch: {},
	methods: {
		async fetchProductDetail() {
			this.detailLoading = true
			productDetail(this.productId)
				.then((res) => {
					this.productDetail = res.data
					this.activeGua = res.data.guarantees[0]
					// 开启录屏
					const channel = { 1: 'chinalife', 2: 'cpic', 4: 'huanong' }[
						this.productDetail.policyType
					]
					const oldChannel = localStorage.getItem('channel')

					if (oldChannel !== channel) {
						localStorage.setItem('channel', channel)
						Recorder.renew()
					}
					if (Recorder.status() !== 'living') {
						Recorder.start({
							channel: 'picc-driving',
							compress: true,
							testServer:
								'https://service.aiins.cn/insurance/api/open/putJsonV2'
						})
					}
				})
				.finally(() => {
					this.detailLoading = false
				})
		},
		async save() {
			if (!this.agreeCheck) {
				this.$message.error('请勾选下方协议')
				return
			}
			try {
				await this.$refs[this.policyholder].validate()
				await this.$refs.carIndo.validate()
			} catch (e) {
				console.error(e)
				return
			}
			this.submiting = true
			try {
				await this.savePayInfo()
			} catch (err) {
				this.$message.error(err.message)
				console.error(err)
			} finally {
				this.submiting = false
				this.submitingTip = ''
				clearInterval(interval)
			}
		},
		savePayInfo() {
			return goPay(this.businessId, {
				guaranteeId: this.activeGua?.id,
				...this.customerForm.carInfo,
				...this.customerForm[this.policyholder],
				isGroup: this.policyholder === 'corporate'
			}).then(({ data: servData }) => {
				// this.$router.push({
				// 	name: 'Payment-No-Require',
				// 	query: {
				// 		businessId: this.businessId,
				// 		productId: this.productId
				// 	}
				// })
				Recorder.submit({
					businessId: this.businessId
				})
				this.$message.success('投保信息已提交')
			})
		},
		onAgree(agree) {
			this.agreeProp = agree.name
			this.agreeShow = true
		},
		onUploadCard(files) {
			this.customerForm.individual.idCard = files
			console.log(this.customerForm)
			const file = files[0]
			file &&
				idCardOcr(file).then(({ data }) => {
					this.customerForm.individual.name = data.name
					this.customerForm.individual.idNumber = data.idNumber
					this.customerForm.individual.address = data.address
					this.customerForm.individual.gender = data.gender == '男' ? 1 : 2
					this.customerForm.individual.birthDate = data.birthDate
					this.customerForm.individual.idType = 0
				})
		},
		onUploadLicenseOcr(files) {
			this.customerForm.corporate.license = files

			const file = files[0]
			file &&
				licenseOcr(file).then(({ data }) => {
					this.customerForm.corporate.certNum = data.certNum
					this.customerForm.corporate.address = data.address
					this.customerForm.corporate.contactName = data.contactName
					this.customerForm.corporate.customerName = data.customerName
				})
		},
		onUploadDrive(files) {
			this.customerForm.carInfo.drive = files
			const file = files[0]
			file &&
				driveOcr(file).then(({ data }) => {
					this.customerForm.carInfo.engineNumber = data.engineNumber
					this.customerForm.carInfo.vin = data.vehicleIdentificationNumber
					this.customerForm.carInfo.tonnage = data.grossWeight
					this.customerForm.carInfo.approvedSeating = data.seatingCapacity
					this.customerForm.carInfo.licensePlate = data.licensePlateNumber
				})
		}
	},
	components: { ProductItem, InsureAddress, Upload }
}
</script>

<style lang="scss" scoped="scoped">
.import {
	padding: 20px;
}
.box-card {
	margin-bottom: 20px;
}
.product-name {
	font-size: 20px;
	font-weight: 600;
	text-align: center;
	margin-block: 20px;
}
.import ::v-deep {
	.el-form {
		display: grid;
		gap: 15px;
		grid-template-columns: 1fr 1fr;
	}
	.el-form-item {
		margin-bottom: 0;
		.el-form-item__content {
			display: flex;
			min-height: 40px;
			align-items: center;
		}
	}

	.el-table__header tr th {
		font-size: 13px;
		color: #333;
		background: #fbfcff;
	}
}
.field {
	width: 100%;
}
.grid {
	display: grid;
	align-items: center;
	gap: 12px;
	grid-template-columns: 1fr auto;
}
.option {
	font-size: 14px;
	padding: 8px;
	cursor: pointer;
	&:active {
		background-color: #f4f4ff;
	}
}
.hide-upload-button ::v-deep .el-upload--picture-card {
	display: none;
}
.payment-form ::v-deep .el-form-item__label {
	line-height: 24px;
	margin-bottom: 0;
}
.append-fix {
	position: absolute;
	right: 1em;
	top: 50%;
	transform: translateY(-50%);
	color: #999;
}
.submit {
	border-radius: 99px;
	// border-radius: 0 99px 99px 0;
	// border: 4px solid #5f88ff;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	padding: 5px;
	background-color: #fff;
	// color: #fff;
	width: 530px;
	margin: 15px auto;

	display: grid;
	grid-template-columns: 2fr 1fr;
	justify-items: stretch;
	gap: 4px;

	.agree {
		padding: 10px 20px;
		border-radius: 99px 0 0 99px;
		background-color: #ebf0ff;
		.check {
			vertical-align: top;
			margin-right: 3px;
		}
	}
	.submit-btn {
		background-color: #5f88ff;
		color: #fff;
		font-weight: 600;
		font-size: 18px;
		letter-spacing: 1px;
		padding: 15px 0 0 30px;
		border-radius: 0 99px 99px 0;
	}
}
</style>
